#!/usr/bin/perl

use PGPLOT;
use lib '/data/MENTOK_2/ste616/EB500/Software/Utilities/TCPExample';
use strict;

my $rdir = "/data/MENTOK_2/ste616/EB500/Software/Utilities/TCPExample";

# We run forever.
while (1) {
    # Wait until we are allowed to use the EB500.
    while (&eb500_reserved() == 1) {
	print "Waiting for EB500 reservation...\n";
	sleep 30;
    }
    print "Reserving the EB500...";

    # Reserve the EB500.
    &reserve_eb500();
    print " done.\n";

    print "Running a scan... ";
    &runscan();
    print " done.\n";

    # Release the EB500.
    print "Releasing the EB500...";
    &release_eb500();
    print " done.\n";

    # Generate the plots.
#    system "python plot_rfiwaterfall.py > waterfallname.out";

    # Assign it as the current plot.
#    chomp(my $pname = `cat waterfallname.out`);
#    system "cp ".$pname." /n/ste616/Documents/rfi_skyplots/waterfall_latest.png";

    # Wait for 20 seconds between measurements.
    print "Waiting until next scan...\n";
    sleep 20;
}

sub runscan {
    # Get the data from the EB500.

    system $rdir."/rfiplot > /dev/null";

    chomp(my $d = `date -u -I'seconds'`);
    my $rsc = sprintf "cp rfi_spectrum.txt spectra/rfispectrum_".$d.".txt";
    system $rsc;
}

sub reserve_eb500 {
    # Prevent other users from calling the EB500.
    open(F, ">".$rdir."/.eb500_reserved");
    print F "true";
    close(F);
}

sub release_eb500 {
    # Allow other users to calling the EB500.
    open(F, ">".$rdir."/.eb500_reserved");
    print F "false";
    close(F);
}

sub eb500_reserved {
    # Check whether the EB500 is reserved.
    chomp(my $reserved = `cat $rdir/.eb500_reserved`);
    $reserved =~ s/\n//g;
    print "reservation check = $reserved\n";
    
    if ($reserved eq "false") {
	return 0;
    } else {
	return 1;
    }
}
